import datetime
import os
import time
import pymediainfo
from cv2 import cv2
from openpyxl import load_workbook

result = os.path.abspath(os.path.join(os.getcwd(), "..")) + "\Result"
resultfile = result + "\\" + "K9B_CAM_Camera_VideoFrame.xlsx"
locators = [["1", 3, 9], ["2", 12, 10], ["3", 26, 9], ["4", 39, 8], ["5", 47, 8], ["6", 55, 8],
            ["7", 3, 11], ["8", 3, 7], ["9", 3, 8], ["10", 11, 12]]
videpfile = r"W:\Python\10-31\pythonDemo2\Result\2021-11-10\2"


# 遍历文件夹
def listdir(path):  # 传入存储的list
    datanames = os.listdir(path)
    file_list = []
    for dataname in datanames:
        print(dataname)
        if os.path.splitext(dataname)[-1] == '.mp4' or os.path.splitext(dataname)[-1] == '.avi':  # 目录下包含.json的文件
            file_list.append(dataname)
    return file_list


def anaylsis_one(filepath):
    woo = 0
    videoframes, lostframes = [], []
    for i in sortdir(filepath):
        print(filepath + "\\" + str(i))
        vCapture = cv2.VideoCapture(filepath + "\\" + str(i))
        status = True
        # 获取视频帧数
        frame_rate = round(vCapture.get(5), 3)
        # 每帧获取时间间隔列表
        interval = []
        # 获取上一帧时间戳,初始帧数时间戳为0
        pre = 0
        frame_count = 0
        timelist = []
        print("----------waiting to analysis-----------")
        while (status):
            time_start = time.time()
            # 获取视频帧
            # status, frame = vCapture.read()
            status = vCapture.grab()
            time_end = time.time()
            # 获取每帧时间戳
            cur = vCapture.get(cv2.CAP_PROP_POS_MSEC)
            # 计算每帧
            interval.append(float((cur - pre) / 1000))
            pre = cur
            timenum2 = time_end - time_start
            woo = float(woo + timenum2)
        print('Analyzing ' + str(vCapture.get(cv2.CAP_PROP_FRAME_COUNT)) + ' Frame.')
        # 总帧数
        frame_count = vCapture.get(cv2.CAP_PROP_FRAME_COUNT)
        # 获取最大丢帧时间戳间隔
        peak_value = round(max(interval), 5)
        # 计算最大丢帧数=(最大丢帧时间戳间隔/单位帧时间戳间隔)-1
        # print(str(peak_value) + "   " + str(frame_rate))
        if frame_rate != 30:
            lost_frame = (float(peak_value) / (float((1 / frame_rate)))) - 1
        elif frame_rate == 30:
            lost_frame = 0
        # print("max_lost_frame: " + str(lost_frame))
        videoframes.append(str(frame_rate))
        lostframes.append(str(round(lost_frame, 4)))
    # print("总时间:" + str(round(woo, 5)))
    return videoframes, lostframes


# 传入两个参数  param1 文件id  param2  video结果
# 写入excel表格 name, videofile
def exce_xlsx(name,videpfile):
    xlsxfile = load_workbook(resultfile)
    if int(name) < 7:
        sheet = xlsxfile['视频帧率测试页']
    elif name == "7":
        sheet = xlsxfile['前置视频帧率测试页']
    elif name == "8":
        sheet = xlsxfile['专业视频']
    elif name in ["9", "10", "11"]:
        sheet = xlsxfile['短视频APP']
    # 获取合并单元格
    list3 = []
    for i in sheet.merged_cells.ranges:
        if "D" in str(i):
            a_num = int(str(i).replace('D', '').split(':')[0])
            for a in range(a_num, a_num + 4, 1):
                list3.append('D' + str(a))
    if name == "10":
        list3 = ['D13', 'D17', 'D18', 'E13', 'E17', 'E18']
    list1, list2 = anaylsis_one(videpfile)
    # 排除合并单元格
    for b, x, y in zip([i for i in locator(str(name)) if i not in list3], list1, list2):
        if int(name) < 7:
            if "D" in b:
                sheet[b] = x
            if "E" in b:
                sheet[b] = x
                sheet[str(b).replace('E', 'F')] = y
        elif int(name) > 7:
            if "D" in b:
                sheet[b] = x
                sheet[str(b).replace('D', 'E')] = y
    xlsxfile.save(resultfile)


# 定位器
def locator(name):
    print("------------------ ")
    listnum = []
    for i in locators:
        if name == i[0]:
            listnum = inputcoord(i[1], i[2])
        if name == "2" and i[0] == "2":
            listnum += inputcoord(22, 4)
        if name == "3" and i[0] == "3":
            listnum += inputcoord(35, 4)
    return listnum


# 定位生成  param字符1  param 字符2 chart, stratid
def inputcoord(startid, num):
    list1, list2 = [], []
    for i in range(startid, startid + num, 1):
        list1.append('D' + str(i))
        list2.append('E' + str(i))
    return list1 + list2


def sortdir1(file_path):
    dir_list = os.listdir(file_path)
    if not dir_list:
        print(file_path + ":文件夹中不存在文件")
    else:
        # 注意，这里使用lambda表达式，将文件按照最后修改时间顺序升序排列
        # os.path.getmtime() 函数是获取文件最后修改时间
        # os.path.getctime() 函数是获取文件最后创建时间
        file_list = []
        for dataname in dir_list:
            if os.path.splitext(dataname)[-1] == '.mp4' or os.path.splitext(dataname)[-1] == '.avi':  # 目录下包含.json的文件
                file_list.append(dataname)
        file_list = sorted(file_list, key=lambda x: os.path.getctime(os.path.join(file_path, x)))
        return file_list


# 文件媒体创建日期转换为秒
def getsecond(fpath):
    media_info = pymediainfo.MediaInfo.parse(fpath)
    data = media_info.to_data()
    timedata = str(data["tracks"][1]["encoded_date"]).split(" ")[1] + " " + \
               str(data["tracks"][1]["encoded_date"]).split(" ")[2]
    return int(time.mktime(time.strptime(timedata, "%Y-%m-%d %H:%M:%S")))


# 按照文件日期=秒 排序
def sortdir(file_path):
    file_list = []
    for dataname in os.listdir(file_path):
        if os.path.splitext(dataname)[-1] == '.mp4' or os.path.splitext(dataname)[-1] == '.avi':  # 目录下包含.json的文件
            file_list.append(dataname)
    file_list = sorted(file_list, key=lambda x: getsecond(os.path.join(file_path, x)))
    return file_list


if __name__ == '__main__':
    # for i in sortdir(r"D:\PyCharmProject\pythonDemo2\Result\2021-11-11\1\Camera"):
    #     print(i)
    # list1 = ['a', 'b', 'c', 'd']
    # list2 = ['a', 'b','e']
    # list1_not_in_list2 = [i for i in list1 if i not in list2]
    # print(list1_not_in_list2)
    for i in range(8, 11, 1):
        exce_xlsx(str(i), r"D:\PyCharmProject\pythonDemo2\Result\2021-11-15" + "\\" + str(i) + "\\Camera")

    # xlsxfile = load_workbook(resultfile)
    # sheet = xlsxfile['视频帧率测试页']
    # list3 = []
    # for i in sheet.merged_cells.ranges:
    #     if "D" in str(i):
    #         a_num = int(str(i).replace('D', '').split(':')[0])
    #         for a in range(a_num, a_num + 4, 1):
    #             list3.append('D' + str(a))
    # print(list3)
